package request;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Request {
    private boolean error = false;
    private String method;
    private String resource;
    private final Map<String, String> headers;

    private String postData;


    private Request() {
        headers = new HashMap<>();
    }

    public boolean isError() {
        return error;
    }

    public String getMethod() {
        return method;
    }

    public String getResource() {
        return resource;
    }

    public String get(String key) {
        if (headers.containsKey(key)) {
            return headers.get(key);
        }

        return "";
    }

    public String getPostData() {
        return postData;
    }

    public static Request parseFromInputStream(InputStream inputStream) throws IOException {
        Request request = new Request();

        byte[] buffer = new byte[2048];

        int count = inputStream.read(buffer);
        if (count <= 0) {
            request.error = true;
            return request;
        }

        String requestInfo = new String(buffer);
        System.out.println(requestInfo);
        List<String> lines = requestInfo.lines().collect(Collectors.toList());

        String[] temp = lines.get(0).split(" ");

        request.method = temp[0];
        request.resource = temp[1];

        int i = 1;
        for (; i < lines.size(); i++) {
            if (lines.get(i).length() == 0) {
                break;
            }
            String[] pair = lines.get(i).split(":", 2);
            request.headers.put(pair[0], pair[1].trim());
        }
        request.postData = lines.get(i + 1);

//        if (request.method.equals("POST")) {
//            System.out.println(request.postData);
//        }

        return request;
    }
}
